 
  

 






<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do;jsessionid=4FCCB481C702D708A7360133D128E359?Id=11 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:28:06 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
<head>
 <title>
  Java Practices -> Constructors in general
 </title>
 <link rel="stylesheet" type="text/css" href="../stylesheet8.css" media="all">
 
 <link rel="shortcut icon" href='../images/favicon.ico' type="image/vnd.microsoft.icon">
 <meta name="description" content="Concise presentations of java programming practices, tasks, and conventions, amply illustrated with syntax highlighted code examples.">
 
 <meta name='keywords' content='invariant,super,this,constructor,java,java programming,java practices,java idiom,java style,java design patterns,java coding conventions,'>
 
 
</head>
 
<body>


<div class='menu-bar'>
 
  <a href='../home/HomeAction.html' title='Table of Contents'>Home</a> |
  <a href='../vote/VoteSummaryAction-2.html' title='View Poll Results'>Poll</a> |
   
  <A href='../feedback/FeedbackAction451f-2.html?Operation=Show' title='Send Your Feedback'>Wiki</a> |
  <b><a href='../source/SourceAction-2.html' title='Grab Source Code'>Source Code</a></b><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |

  <a href='http://www.web4j.com/Java_Web_Application_Framework_Overview.jsp?From=1' title='Free Download - Java Web Application Framework'><b>WEB4J</b></a> |
  
  <a href='http://www.date4j.net/' title='Replacement for java.util.Date'><b>DATE4J</b></a> |

   <a href='../references/ReferencesAction-2.html' title='References'>Links</a>
   
  <form action='http://www.javapractices.com/search/SearchAction.do' method='get' class='search-form'>
   <input type='text' name='SearchTerms' value="" size=12 maxlength=50 class='search'>
   <input type='submit' value="Search">
  </form>
 
</div>

<P>



  

 






<p class="display-messages">

 

 

</p>


<div class="main-layout">
 
   

 




<div class='page-title'>Constructors in general</div>

<div class='main-body'>
 
<br>Constructors :
<ul>
<li>
if <tt>super</tt> or <tt>this</tt> are called, they can only be called on the first
line of the constructor</li>

<li>
an <tt>Exception</tt> can be thrown if a parameter is invalid</li>

<li>
you should ensure that the constructed object is in a <a href="TopicAction0d31-2.html">valid state</a></li>

<li>
constructors should <a href='TopicAction6581-2.html'>never call an overridable method</a> (an overridable method
is one which is neither <tt>private</tt>, <tt>static</tt>, nor <tt>final)</tt></li>

<li>
constructors are never <tt>synchronized</tt></li>

<li>
<a href="TopicAction79e9-2.html">constructors can be private</a>, in order to restrict
construction</li>
</ul>
Note that a conventional distinction is made in Java between the 
"<a href='http://java.sun.com/docs/books/jls/second_edition/html/classes.doc.html#16823'>default constructor</a>" 
and a "no-argument constructor":
<ul>
<li>
the <em>default</em> constructor is the constructor provided by the system in the
absence of any constructor provided by the programmer. Once a programmer
supplies any constructor whatsoever, the default constructor is no longer
supplied.</li>

<li>
a <em>no-argument</em> constructor, on the other hand, is a constructor provided
by the programmer which takes no arguments.</li>
</ul>

This distinction is necessary because the behavior of the two kinds of constructor are 
unrelated : a default constructor has a fixed behavior defined by Java, while the 
behavior of a no-argument constructor is defined by the application programmer.

<P><b>Example</b>
<p><tt>Resto</tt> is an <a href="TopicActiond838-2.html">immutable</a> class, since
its state cannot change after construction. Note that
<ul>
<li>
all validation is performed in its constructor</li>

<li>
almost all of its javadoc is concerned with stating precisely what is to
be passed to the constructor</li>
</ul>
<br>
<PRE>

<span class='keyword'>package</span> hirondelle.fish.main.resto;

<span class='keyword'>import</span> hirondelle.web4j.model.ModelCtorException;
<span class='keyword'>import</span> hirondelle.web4j.model.ModelUtil;
<span class='keyword'>import</span> hirondelle.web4j.model.Id;
<span class='keyword'>import</span> hirondelle.web4j.security.SafeText;
<span class='keyword'>import</span> hirondelle.web4j.model.Decimal;
<span class='keyword'>import</span> <span class='keyword'>static</span> hirondelle.web4j.model.Decimal.ZERO;
<span class='keyword'>import</span> hirondelle.web4j.model.Check;
<span class='keyword'>import</span> hirondelle.web4j.model.Validator;
<span class='keyword'>import</span> <span class='keyword'>static</span> hirondelle.web4j.util.Consts.FAILS;

<span class='comment'>/** Model Object for a Restaurant. */</span>
<span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>class</span> Resto {

  <span class='comment'>/**
   Full constructor.
    
   @param aId underlying database internal identifier (optional) 1..50 characters
   @param aName of the restaurant (required), 2..50 characters
   @param aLocation street address of the restaurant (optional), 2..50 characters
   @param aPrice of the fish and chips meal (optional) $0.00..$100.00
   @param aComment on the restaurant in general (optional) 2..50 characters
  */</span>
  <span class='keyword'>public</span> Resto(
    Id aId, SafeText aName, SafeText aLocation, Decimal aPrice, SafeText aComment
  ) <span class='keyword'>throws</span> ModelCtorException {
    fId = aId;
    fName = aName;
    fLocation = aLocation;
    fPrice = aPrice;
    fComment = aComment;
    validateState();
  }
  
  <span class='keyword'>public</span> Id getId() { <span class='keyword'>return</span> fId; }
  <span class='keyword'>public</span> SafeText getName() {  <span class='keyword'>return</span> fName; }
  <span class='keyword'>public</span> SafeText getLocation() {  <span class='keyword'>return</span> fLocation;  }
  <span class='keyword'>public</span> Decimal getPrice() { <span class='keyword'>return</span> fPrice; }
  <span class='keyword'>public</span> SafeText getComment() {  <span class='keyword'>return</span> fComment; }

  <span class='keyword'>@Override</span> <span class='keyword'>public</span> String toString(){
    <span class='keyword'>return</span> ModelUtil.toStringFor(<span class='keyword'>this</span>);
  }
  
  <span class='keyword'>@Override</span> <span class='keyword'>public</span>  <span class='keyword'>boolean</span> equals(Object aThat){
    Boolean result = ModelUtil.quickEquals(<span class='keyword'>this</span>, aThat);
    <span class='keyword'>if</span> ( result ==  <span class='keyword'>null</span> ) {
      Resto that = (Resto) aThat;
      result = ModelUtil.equalsFor(
        <span class='keyword'>this</span>.getSignificantFields(), that.getSignificantFields()
      );
    }
    <span class='keyword'>return</span> result;
  }
  
  <span class='keyword'>@Override</span> <span class='keyword'>public</span> <span class='keyword'>int</span> hashCode(){
    <span class='keyword'>if</span> ( fHashCode == <span class='literal'>0</span> ){
      fHashCode = ModelUtil.hashCodeFor(getSignificantFields());
    }
    <span class='keyword'>return</span> fHashCode;
  }
  
  <span class='comment'>// PRIVATE //
</span>  <span class='keyword'>private</span> <span class='keyword'>final</span> Id fId;
  <span class='keyword'>private</span> <span class='keyword'>final</span> SafeText fName;
  <span class='keyword'>private</span> <span class='keyword'>final</span> SafeText fLocation;
  <span class='keyword'>private</span> <span class='keyword'>final</span> Decimal fPrice;
  <span class='keyword'>private</span> <span class='keyword'>final</span> SafeText fComment;
  <span class='keyword'>private</span> <span class='keyword'>int</span> fHashCode;
  
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> Decimal HUNDRED = Decimal.from(<span class='literal'>"100"</span>);

  <span class='keyword'>private</span> <span class='keyword'>void</span> validateState() <span class='keyword'>throws</span> ModelCtorException {
    ModelCtorException ex = <span class='keyword'>new</span> ModelCtorException();
    <span class='keyword'>if</span> ( FAILS == Check.optional(fId, Check.range(<span class='literal'>1</span>,<span class='literal'>50</span>)) ) {
      ex.add(<span class='literal'>"Id is optional, 1..50 chars."</span>);
    }
    <span class='keyword'>if</span> ( FAILS == Check.required(fName, Check.range(<span class='literal'>2</span>,<span class='literal'>50</span>)) ) {
      ex.add(<span class='literal'>"Restaurant Name is required, 2..50 chars."</span>);
    }
    <span class='keyword'>if</span> ( FAILS == Check.optional(fLocation, Check.range(<span class='literal'>2</span>,<span class='literal'>50</span>)) ) {
      ex.add(<span class='literal'>"Location is optional, 2..50 chars."</span>);
    }
    Validator[] priceChecks = {Check.range(ZERO, HUNDRED), Check.numDecimalsAlways(<span class='literal'>2</span>)};
    <span class='keyword'>if</span> ( FAILS == Check.optional(fPrice, priceChecks)) {
      ex.add(<span class='literal'>"Price is optional, 0.00 to 100.00."</span>);
    }
    <span class='keyword'>if</span> ( FAILS == Check.optional(fComment, Check.range(<span class='literal'>2</span>,<span class='literal'>50</span>))) {
      ex.add(<span class='literal'>"Comment is optional, 2..50 chars."</span>);
    }
    <span class='keyword'>if</span> ( ! ex.isEmpty() ) <span class='keyword'>throw</span> ex;
  }
  
  <span class='keyword'>private</span> Object[] getSignificantFields(){
    <span class='keyword'>return</span> <span class='keyword'>new</span> Object[] {fName, fLocation, fPrice, fComment};
  }
}
 
</PRE>
<br>
<br>
<br>

</div>




<div class='topic-section'>See Also :</div>
<div class='main-body'>
 
  
  <a href='TopicAction5d11-2.html?Id=5'>Validate method arguments</a> <br>
 
  
  <a href='TopicAction0d31-2.html?Id=6'>Validate state with class invariants</a> <br>
 
  
  <a href='TopicAction9b86-2.html?Id=14'>Initializing fields to 0-false-null is redundant</a> <br>
 
  
  <a href='TopicActiond838-2.html?Id=29'>Immutable objects</a> <br>
 
  
  <a href='TopicAction79e9-2.html?Id=40'>Private constructor</a> <br>
 
  
  <a href='TopicActionfbbc-2.html?Id=84'>Avoid JavaBeans style of construction</a> <br>
 
  
  <a href='TopicAction6581-2.html?Id=215'>Constructors shouldn't call overridables</a> <br>
 
</div>


<div class='topic-section'>Would you use this technique?</div>
<div class='main-body'>
  
  <form action="http://www.javapractices.com/vote/AddVoteAction.do" method='post'>
    Yes<input type='radio' name='Choice' value='Y' >
    &nbsp;&nbsp;No<input type='radio' name='Choice' value='N'>
    &nbsp;&nbsp;Undecided<input type='radio' name='Choice' value="?" >
    &nbsp;&nbsp;<input type=submit value="Vote" >
    <input type='hidden' name='Operation' value='Apply'>
    <input type='hidden' name='TopicId' value='11'>
  </form>
</div>

<div style='height:10.0em;'></div>

 
 
</div>

  

 





<div align='center' class='legalese'>  
&copy; 2011 Hirondelle Systems |
<a href='../source/SourceAction-2.html'><b>Source Code</b></a><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |
<a href="mailto:webmaster@javapractices.com">Contact</a> |
<a href="http://creativecommons.org/licenses/by-nc-sa/1.0/">License</a> |
<a href='../apps/cjp.rss'>RSS</a>
<!-- ukey="2AC36CD2" -->
<!-- ckey="16DF3D87" -->
<br>

 Individual code snippets can be used under this <a href='../LICENSE.txt'>BSD license</a> - Last updated on June 6, 2010.<br>
 Over 150,000 unique IPs last month - <span title='Java Practices 2.6.5, Mon May 16 00:00:00 EDT 2011'>Built with</span> <a href='http://www.web4j.com/'>WEB4J</a>.<br>
 - In Memoriam : Bill Dirani -
</div>

<script src="../../www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-2633428-1";
urchinTracker();
</script>



</body>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do;jsessionid=4FCCB481C702D708A7360133D128E359?Id=11 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:28:07 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
</html>
